package com.example.administrator.smartbutler.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.os.EnvironmentCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.smartbutler.R;
import com.example.administrator.smartbutler.entity.MyUser;
import com.example.administrator.smartbutler.ui.CourierActivity;
import com.example.administrator.smartbutler.ui.LoginActivity;
import com.example.administrator.smartbutler.ui.PhoneActivity;
import com.example.administrator.smartbutler.utils.UtilTools;
import com.example.administrator.smartbutler.view.CustomDialog;

import java.io.ByteArrayOutputStream;
import java.io.File;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 项目名:SmartButler
 * 包名:Fragment
 * 文件名：UserInfoFragment
 * 创建者：justin
 * Created by Administrator on 2017/12/19.
 * 描述：TODO
 */

public class UserInfoFragment extends Fragment implements View.OnClickListener {


    private EditText userInfo_username;
    private RadioGroup userInfo_sex;
    private EditText userInfo_introduction;
    private EditText userInfo_age;

    private Button userInfo_btn_exit;

    private TextView userInfo_edit_user;

    private Button userInfo_btn_update;

    private RadioButton userInfo_man;

    private RadioButton userInfo_woman;

    private boolean isSex;

    private CircleImageView circleImageView;//圆形头像

    private CustomDialog customDialog;

    private Button btn_camera;//拍照

    private Button btn_picture;//图库

    private Button btn_cancel;//取消

    private TextView userInfo_courier;

    private TextView userInfo_phone;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_userinfo, null);

        findView(view);

        return view;
    }

    //初始化数据
    private void findView(View view) {

        userInfo_username = (EditText) view.findViewById(R.id.userInfo_username);
        userInfo_sex = (RadioGroup) view.findViewById(R.id.userInfo_sex);
        userInfo_introduction = (EditText) view.findViewById(R.id.userInfo_introduction);
        userInfo_age = (EditText) view.findViewById(R.id.userInfo_age);
        userInfo_btn_exit = (Button) view.findViewById(R.id.userInfo_btn_exit);
        userInfo_edit_user = (TextView) view.findViewById(R.id.userInfo_edit_user);
        userInfo_btn_update = (Button) view.findViewById(R.id.userInfo_btn_update);
        userInfo_man = (RadioButton) view.findViewById(R.id.userInfo_man);
        userInfo_woman = (RadioButton) view.findViewById(R.id.userInfo_woman);
        circleImageView = (CircleImageView) view.findViewById(R.id.profile_image);
        userInfo_courier = (TextView) view.findViewById(R.id.userInfo_courier);
        userInfo_phone = (TextView) view.findViewById(R.id.userInfo_phone);


        //读取图片
        UtilTools.getImageToShare(getActivity(), circleImageView);


        //设置dialog
        customDialog = new CustomDialog(getActivity(), 500, 300, R.layout.dialog_photo, R.style.theme_dialog, Gravity.BOTTOM, R.style.pop_anim_style);
        //屏幕外点击无效
        customDialog.setCancelable(false);

        //这三个按钮在 dialog里面
        btn_camera = (Button) customDialog.findViewById(R.id.btn_camera);
        btn_picture = (Button) customDialog.findViewById(R.id.btn_picture);
        btn_cancel = (Button) customDialog.findViewById(R.id.btn_cancel);

        circleImageView.setOnClickListener(this);
        userInfo_btn_update.setOnClickListener(this);
        userInfo_btn_exit.setOnClickListener(this);
        userInfo_edit_user.setOnClickListener(this);
        btn_camera.setOnClickListener(this);
        btn_picture.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);

        userInfo_courier.setOnClickListener(this);
        userInfo_phone.setOnClickListener(this);


        //单选按钮组的点击监听
        userInfo_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.userInfo_man:
                        isSex = true;
                        break;
                    case R.id.userInfo_woman:
                        isSex = false;
                        break;

                }
            }
        });

        //设置只读
        setEnable(false);

        //获取当前用户的信息
        MyUser userInfo = BmobUser.getCurrentUser(MyUser.class);

        //初始化赋值
        userInfo_username.setText(userInfo.getUsername());
        userInfo_age.setText(userInfo.getAge() + "");
        userInfo_introduction.setText(userInfo.getIntroduction());
        if (userInfo.isSex()) {
            userInfo_man.setChecked(true);
        } else {
            userInfo_woman.setChecked(true);
        }

    }

    //设置输入的只读
    private void setEnable(boolean is) {

        userInfo_username.setEnabled(is);
        userInfo_sex.setEnabled(is);
        userInfo_introduction.setEnabled(is);
        userInfo_age.setEnabled(is);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userInfo_btn_exit:
                MyUser.logOut();   //清除缓存用户对象
                BmobUser currentUser = MyUser.getCurrentUser(); // 现在的currentUser是null了

                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();

                break;
            case R.id.userInfo_edit_user:
                setEnable(true);
                userInfo_btn_update.setVisibility(View.VISIBLE);
                break;
            case R.id.userInfo_btn_update:

                String name = userInfo_username.getText().toString().trim();

                String age = userInfo_age.getText().toString().trim();
                String introduction = userInfo_introduction.getText().toString().trim();

                if (!TextUtils.isEmpty(name) & !TextUtils.isEmpty(age)) {

                    //获取当前用户的信息
                    MyUser userCurr = BmobUser.getCurrentUser(MyUser.class);

                    MyUser userInfo = new MyUser();

                    //因为一些Bmob的原因当前的用户名不能跟原来一样，所以跟原来一样的不保存
                    if (!userCurr.getUsername().equals(name)) {
                        userInfo.setUsername(name);
                    }

                    if (TextUtils.isEmpty(introduction)) {
                        introduction = "这个人很懒，什么都没写";
                    }

                    userInfo.setSex(isSex);
                    userInfo.setAge(Integer.parseInt(age));
                    userInfo.setIntroduction(introduction);

                    BmobUser bmobUser = BmobUser.getCurrentUser();

                    userInfo.update(bmobUser.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                //修改成功
                                setEnable(false);
                                userInfo_btn_update.setVisibility(View.GONE);
                                Toast.makeText(getActivity(), R.string.updateSuccess, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "修改出错" + e.getErrorCode(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });


                } else {

                    Toast.makeText(getActivity(), "输入不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.profile_image:
                customDialog.show();
                break;
            case R.id.btn_cancel:
                customDialog.dismiss();
                break;
            case R.id.btn_picture:
                toPicture();

                break;
            case R.id.btn_camera:
                toCamera();
                break;
            case R.id.userInfo_courier:
                startActivity(new Intent(getActivity(),CourierActivity.class));
                break;
            case R.id.userInfo_phone:
                startActivity(new Intent(getActivity(),PhoneActivity.class));
                break;

        }

    }


    private static final String PHOTO_IMAGE_FILE_NAME = "fileImg.jpg";

    private static final int CAMERA_REQUEST_CODE = 100;

    private static final int PHOTO_REQUEST_CODE = 101;

    private static final int REQUEST_CODE = 102;

    private File tempFile = null;

    //跳转相机
    private void toCamera() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //判断内存卡是否可用，可用的话就进行存储
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_IMAGE_FILE_NAME)));

        startActivityForResult(intent, CAMERA_REQUEST_CODE);

        customDialog.dismiss();

    }

    //跳转图库
    private void toPicture() {

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PHOTO_REQUEST_CODE);
        customDialog.dismiss();

    }

    //返回值
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != 0) {
            switch (requestCode) {
                case PHOTO_REQUEST_CODE:
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_IMAGE_FILE_NAME);
                    startPhotoZoom(Uri.fromFile(tempFile));
                    break;
                case REQUEST_CODE:

                    //有可能点击舍弃
                    if (data != null) {
                        //拿到图片设置
                        setImageToView(data);
                        //既然设置了图片，原先就应该删除
                        if (tempFile != null) {

                            tempFile.delete();
                        }
                    }

                    break;


            }
        }

    }

    //裁剪图片
    private void startPhotoZoom(Uri uri) {

        if (uri == null) {
            Log.e("error", "uri==null");
            return;
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        //设置裁剪
        intent.putExtra("crop", "true");

        //设置裁剪宽高
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //裁剪图片的质量
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);

        //发送数据
        intent.putExtra("return-data", true);

        //跳转

        startActivityForResult(intent, REQUEST_CODE);

    }


    //设置图片
    private void setImageToView(Intent data) {

        Bundle bundle = data.getExtras();
        if (bundle != null) {

            Bitmap bitmap = bundle.getParcelable("data");

            circleImageView.setImageBitmap(bitmap);

        }

    }

    //页面销毁
    @Override
    public void onDestroy() {
        super.onDestroy();

        UtilTools.putImageToShare(getActivity(), circleImageView);
    }
}
